import Vue from 'vue'
async function Request(options) {
  const {
    method = 'get',
    ...extra
  } = options;
  const params = await uni.request({
    ...extra,
    method,
    timeout: 20000,
    header: Request.mergeHeader(),
  })
  if (!params.length) return Request.errow('服务器错误，请截图联系客服处理')
  if (params[0] && params[0].errMsg == "request:fail timeout") return Request.errow('请求超时，请稍后重试')
  if (params.length == 1) return Request.errow(params[0].errMsg)
  const {
    statusCode,
    data = {}
  } = params[1]
  if (statusCode !== 200) return Request.errow(`服务器错误，错误码：${statusCode}，请截图联系客服处理`)
  if (data.code == 401) return Request.refresh(options)
  if (data.code !== 200) return Request.errow(data.message || `服务器错误，错误码：${data.code}，请截图联系客服处理`)
  return data
}

Request.refresh = async function (options) {
  const code = await Vue.prototype.$store.dispatch('refreshToken');
  let data = {
    code: 0,
    data: null
  }
  if (code == 200) data = await Request[options.method](options);
  return data
};

Request.mergeHeader = function () {
  const header = {}
  if (Vue.prototype.$store.getters.token) {
    header['Authori-zation'] = `TOKEN_USER:${Vue.prototype.$store.getters.token}`
  }
  return header
};

Request.errow = function (msg) {
  Vue.prototype.$dialog({ content: msg })
  return {
    code: 0,
    data: null
  }
}

Request.get = function (options) {
  return Request({
    ...options,
    method: 'get'
  });
};

Request.post = function (options) {
  return Request({
    ...options,
    method: 'post'
  });
};

Request.put = function (options) {
  return Request({
    ...options,
    method: 'put'
  });
};

export default Request;